import {createStore} from "vuex";
import $localStorage from "@/api/storage/localStorage";
import router from "@/router/router";
import elementApp from "@/main";

const Utils = {
    checkTokenIsNull(item) {
        if (item == null) {
            window.location.href = "/login"
        }
    }
}
export default createStore({
    state: {
        expire: '',
        count: 0,
        user: null,
        token: null,
    },
    //进行数据更新，改变数据状态   store.commit('xx')
    mutations: {
        increment(state) {
            state.count++
        },
        decCount(state) {
            state.count--
        },
        setToken(state, token, expire) {
            state.token = token
            state.expire = Date.parse(expire)
        },
        setUser(state, user) {
            state.user = user
        }
    },
    //执行动作，数据请求 store.dispatch('xx')
    actions: {
        decCount({commit}) {
            commit('decCount')
        },
        increment({commit}) {
            commit('increment')
        },
        setToken({commit}, token, expire) {
            commit('setToken', token, expire)
        },
        setUser({commit}, user) {
            commit('setUser', user)
        }
    },
    //获取到最终的数据结果
    getters: {
        getCount(state) {
            return state.count++
        },
        getToken(state) {
            let token = state.token;
            if (token == null) {
                token = $localStorage.get("token")
                Utils.checkTokenIsNull(token)
            }
            return token
        },
        getUser(state) {
            let user = state.user;
            if (user==null){
                let item = JSON.parse(                sessionStorage.getItem('store'));
                console.log(item)
                if (item.user==null){
                    router.push("/login")
                }
                state.user=item.user
            }
            return state.user
        }
    }
})
